<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=8" >
	<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >
	<title>Camera</title>
	<script type="text/javascript" src="../jquery-1.11.3.min.js"></script>
	<script type="text/javascript" src="../common.js"></script>
	<script type="text/javascript">
		var urlParams = getUrlParams();

		// 需要设置的参数：
//		type 类型：
//			1. 人证对比（查询征信）
//			2. 人脸识别(登录)
//			3. 人像拍摄（查询）
//			4. 资料拍照（查询）
//			5. 身份证识别

//		设备的高宽（有1，2则使用同高宽）


        var DeviceMain;//主头
        var DeviceAssist;//副头
        var VideoMain;//主头
        var VideoAssist;//副头
        var videoCapMain;
        var videoCapAssist;

        var PicPath;
        var initFaceDetectSuccess;
        var readIDcard = false;

        var VideoSubType = {
            "YUY2": 1,
            "MJPG": 2,
            "UYVY": 4
		};
        var mainSubType = "YUY2";
        var assistSubType = "MJPG";

        function plugin()
        {
            return document.getElementById('view1');
        }

        function MainView()
        {
            return document.getElementById('view1');
        }

        function AssistView()
        {
            return document.getElementById('view2');
        }

        function addEvent(obj, name, func)
        {
            if (obj.attachEvent) {
                obj.attachEvent("on"+name, func);
            } else {
                obj.addEventListener(name, func, false);
            }
        }
        
        function OpenVideo(videoType)
        {
			if(videoType == 1){
				 OpenVideoMain();
			} else if(videoType == 2){
				OpenVideoAssist();
			} else {
				
				OpenVideoMain();
				OpenVideoAssist();
			}

	        
        }
        function CloseVideo(videoType)
        {
        	if(videoType == 1){
        		 CloseVideoMain();
			} else if(videoType == 2){
				CloseVideoAssist();
			} else {
				CloseVideoMain();
				CloseVideoAssist();
			}

	        
        }
        function CloseVideoMain()
        {
            if (VideoMain)
            {
                plugin().Video_Release(VideoMain);
                VideoMain = null;

                MainView().View_SetText("", 0);
            }
        }
        function CloseVideoAssist()
        {
            if (VideoAssist)
            {
                plugin().Video_Release(VideoAssist);
                VideoAssist = null;

                AssistView().View_SetText("", 0);
            }
        }

        function OpenVideoMain()
        {
            CloseVideoMain();

            if (!DeviceMain)
                return;

            var SelectType = 1;

//            var nResolution = plugin().Device_GetResolutionCountEx(DeviceMain, SelectType);

            var nResolution = 0;

            VideoMain = plugin().Device_CreateVideo(DeviceMain, nResolution, SelectType);
            console.log('video main:', VideoMain, '; res: ' , nResolution,  ';type: ', SelectType);
            if (VideoMain)
            {
				var open = plugin().View_SelectVideo(VideoMain);
				console.log('video open: ', open);
				plugin().View_SetText("打开视频中，请等待...", 0);


            }
        }

        function OpenVideoAssist()
        {
            CloseVideoAssist();

            if (!DeviceAssist)
                return;


            var SelectType = VideoSubType[assistSubType] || 0;

            var nResolution = 0;

            VideoAssist = plugin().Device_CreateVideo(DeviceAssist, nResolution, SelectType);
            if (VideoAssist)
            {
                AssistView().View_SelectVideo(VideoAssist);
                AssistView().View_SetText("打开视频中，请等待...", 0);
            }
        }


        function Load()
        {
            var cameraType = parseInt(urlParams.type);
            console.log("cameraType"+urlParams.type);
            console.log("facRect"+urlParams.facRect);
            var facRect= urlParams.facRect;
            console.log("facRect1"+facRect);
            console.log("width:"+urlParams.width);
            console.log("height:"+urlParams.width);
            var width=parseInt(urlParams.width);
            var height=parseInt(urlParams.height);
            if(cameraType==2||cameraType==3){
                $("#view2").attr("width",width);
                $("#view2").attr("height",height);
			}else{
                $("#view1").attr("width",width);
                $("#view1").attr("height",height);
			}
          //设备接入和丢失
	        //type设备类型， 1 表示视频设备， 2 表示音频设备
	        //idx设备索引
	        //dbt 1 表示设备到达， 2 表示设备丢失
            addEvent(plugin(), 'DevChange', function (type, idx, dbt) 
			{
			    console.log("dev come");
				if(1 == type)//视频设备
				{
                    console.log("dev come 1");
					if(1 == dbt)//设备到达
					{
                        console.log("dev come 2");
						var deviceType = plugin().Global_GetEloamType(1, idx);
						if(1 == deviceType)//主摄像头
						{
                            console.log("dev come main");
							if(null == DeviceMain)
							{
                                console.log("dev come create dev");
								DeviceMain = plugin().Global_CreateDevice(1, idx);										
								if(cameraType == 1 || cameraType == 4 || cameraType == 5){
                                    console.log("open main");
									OpenVideo(1);
								} else {
								    MainView().style.display = 'none';
								}
//								1. 人证对比（查询征信）
//								2. 人脸识别(登录)
//								3. 人像拍摄（查询）
//								4. 资料拍照（查询）
//								5. 身份证识别
							}
						}
						else if(2 == deviceType || 3 == deviceType)//辅摄像头
						{
                            console.log("dev assist");
							if(null == DeviceAssist)
							{
                                console.log("dev assist 1");
								DeviceAssist = plugin().Global_CreateDevice(1, idx);										
								if(DeviceAssist)
								{
                                    console.log("dev assist2");
									initFaceDetectSuccess = plugin().InitFaceDetect();
                                    console.log("dev assist3:"+initFaceDetectSuccess);
									if(cameraType == 1 || cameraType == 2 || cameraType == 3){
                                        console.log("open assist");
										OpenVideo(2);
									} else {
									    AssistView().style.display = 'none';
									}
								}
							}
						}
					}
					else if(2 == dbt)//设备丢失
					{
						if (DeviceMain) 
						{
                            if (plugin().Device_GetIndex(DeviceMain) == idx) 
							{
                                CloseVideoMain();
                                plugin().Device_Release(DeviceMain);
                                DeviceMain = null;

                            }
                        }
						
                        if (DeviceAssist) 
						{
                            if (plugin().Device_GetIndex(DeviceAssist) == idx) 
							{
                                CloseVideoAssist();
                                plugin().Device_Release(DeviceAssist);
                                DeviceAssist = null;

                            }
                        }
					}
				}
            });

	
	        addEvent(plugin(), 'IdCard', function(ret)
	        {
		        if (1 == ret)
		        {

		        }
	        });
	    
	
	        	
	
	        addEvent(plugin(), 'MoveDetec', function(video, id)
	        {
		        // 自动拍照事件	
	        });
	
	        
		
	        var title = document.title;
	        document.title = title + plugin().version;
		
	        MainView().Global_SetWindowName("view");
	        AssistView().Global_SetWindowName("view");

	        var ret;
			ret = plugin().Global_InitDevs();
			console.log("device init"+ret);
			if(ret)
			{
				//进行人脸识别初始化时，视频应处于关闭状态
				 plugin().InitFaceDetect();
			}

			if( !plugin().Global_VideoCapInit())
			{
				alert("初始化失败！");
			}
            
            
            //			1. 人证对比（查询征信）
//			2. 人脸识别(登录)
//			3. 人像拍摄（查询）
//			4. 资料拍照（查询）
//			5. 身份证识别
//            addEvent(plugin(), 'DevChange', devChangeMain);
//            if (false) {
           /* switch (cameraType) {
                // 1. 人证对比（查询征信）
				case 1:
				    addEvent(plugin(), 'DevChange', devChangeBoth);
				    break;
				// 2. 人脸识别(登录)
				case 2:
				    addEvent(plugin(), 'DevChange', devChangeAssist);
				    MainView().style.display = 'none';

				    break;
				//人像拍摄（查询）
				case 3:
                    addEvent(plugin(), 'DevChange', devChangeAssist);
                    MainView().style.display = 'none';
				    break;
				// 资料拍照（查询）
				case 4:
                    addEvent(plugin(), 'DevChange', devChangeMain);
                    AssistView().style.display = 'none';
				    break;
				// 身份证识别
				case 5:
                    addEvent(plugin(), 'DevChange', devChangeMain);

                    AssistView().style.display = 'none';
                    addEvent(plugin(), 'IdCard', idCardHandle);
                    break;
				}*/
//            }
			function devChangeBoth (type, idx, dbt) {
                devChangeHandle(3, type, idx, dbt);
			}

			function devChangeMain (type, idx, dbt) {
                devChangeHandle(1, type, idx, dbt);
			}
			/**
			 * 开启辅摄像头
			 *
			 **/
			function devChangeAssist(type, idx, dbt) {
                devChangeHandle(2, type, idx, dbt);
			}
			/**
			 * devChange事件处理
			 * @param device 1,2,3
			 * @param type	设备类型， 1 表示视频设备， 2 表示音频设备
			 * @param idx   设备索引
			 * @param dbt	1 表示设备到达， 2 表示设备丢失
			 * return void
			 **/
			function devChangeHandle (device, type, idx, dbt) {
                if (1 == type)//视频设备
                {
                    if (1 == dbt)//设备到达
                    {
                        var deviceType = plugin().Global_GetEloamType(1, idx);
                        if ((device === 1 || device === 3) && 1 == deviceType)//主摄像头
                        {
                            if (null == DeviceMain) {
                                DeviceMain = plugin().Global_CreateDevice(1, idx);
                                console.log('device main: ', DeviceMain);
                                if (DeviceMain) {
                                    console.log('device: ', plugin().Device_GetFriendlyName(DeviceMain));
                                    OpenVideoMain();
                                }
                            }
                        } else if ((device === 2 || device === 3) && 2 == deviceType || 3 == deviceType)//辅摄像头
                        {
                            if (null == DeviceAssist) {
                                DeviceAssist = plugin().Global_CreateDevice(1, idx);
                                if (DeviceAssist) {
                                    initFaceDetectSuccess = plugin().InitFaceDetect();

                                    OpenVideoAssist();
                                }
                            }
                        }
                    }
                    else if (2 == dbt)//设备丢失
                    {
                        console.log('device lost.');
                        if (DeviceMain) {
                            if (plugin().Device_GetIndex(DeviceMain) == idx) {
                                CloseVideoMain();
                                plugin().Device_Release(DeviceMain);
                                DeviceMain = null;
                            }
                        }

                        if (DeviceAssist) {
                            if (plugin().Device_GetIndex(DeviceAssist) == idx) {
                                CloseVideoAssist();
                                plugin().Device_Release(DeviceAssist);
                                DeviceAssist = null;
                            }
                        }
                    }
                }

			}
            addEvent(plugin(), 'Deskew', function(video, view, list)
            {
                // 纠偏回调事件
                var count = plugin().RegionList_GetCount(list);
                for (var i = 0; i < count; ++i)
                {
                    var region = plugin().RegionList_GetRegion(list, i);

                    var x1 = plugin().Region_GetX1(region);
                    var y1 = plugin().Region_GetY1(region);

                    var width = plugin().Region_GetWidth(region);
                    var height = plugin().Region_GetHeight(region);

                    plugin().Region_Release(region);
                }

                plugin().RegionList_Release(list);
            });

            plugin().Global_SetWindowName("view1");

            var ret;
            ret = plugin().Global_InitDevs();
            if(ret)
            {
                //进行人脸识step别初始化时，视频应处于关闭状态
                plugin().InitFaceDetect();
            }

            if( !plugin().Global_VideoCapInit())
            {
                alert("初始化失败！");
            }
            console.log("initFaceDetectSuccess1:"+initFaceDetectSuccess);
            if(cameraType == 1 || cameraType == 2 || cameraType == 3){
                if(facRect=='true'){
                    OpenVerifyFacRect({checked:true});
				}
			}
        }

        function Unload()
        {
            if (VideoMain)
            {
                MainView().View_SetText("", 0);
                plugin().Video_Release(VideoMain);
                VideoMain = null;
            }
            if(DeviceMain)
            {
                plugin().Device_Release(DeviceMain);
                DeviceMain = null;
            }
            if (VideoAssist)
            {
                AssistView().View_SetText("", 0);
                plugin().Video_Release(VideoAssist);
                VideoAssist = null;
            }
            if(DeviceAssist)
            {
                plugin().Device_Release(DeviceAssist);
                DeviceAssist = null;
            }

            StopIDCard();

            plugin().Global_DeinitDevs();
            console.log("unload success");

            //进行人脸识别反初始化时，视频应处于关闭状态
            plugin().DeinitFaceDetect();
            console.log("face unload success");
        }


        function readIdCardImg (index){
            var image = plugin().Global_GetIdCardImage(index);
            var fmt = 2;  // 图片格式 13 为png，2为jpg
            var quantity = 0x0800; // 图片质量，0为最佳
            var prefix = 'data:image/png;base64,'; // 注意图片格式
            return prefix + plugin().Image_GetBase64(image, fmt, quantity);
        }

        function readIdCardData () {
//                姓名 1
//                性别 2
//                民族 3
//                出生年 4
//                出生月 5
//                出生日 6
//                住址 7
//                身份证号码 8
//                签发机关 9
//                有效期限年(起) 10
//                有效期限月(起) 11
//                有效期限日(起) 12
//                有效期限年(止) 13
//                有效期限月(止) 14
//                有效期限日(止) 15
//                芯片序列号 16
            StopIDCard();
            console.log('read id card start.');
            if (plugin().Global_InitIdCard()) {
                var ret = plugin().Global_ReadIdCard();
                if (ret) {
                    var data = [], result;
                    for (var i = 1; i <= 16; i++) {
                        data.push(plugin().Global_GetIdCardData(i));
                    }
                    result = {
                        name: data[0],
                        sex: data[1],
                        nation: data[2],
                        birthday: data[3] + '-' + data[4] + '-' + data[5],
                        address: data[6],
                        id: data[7],
                        dept: data[8],
                        startDate: data[9] + '-' + data[10] + '-' + data[11],
                        expired: data[12] + '-' + data[13] + '-' + data[14],
                        no: data[15]
                    };
                    result.avatar = readIdCardImg (1);
                    result.front = readIdCardImg(2);
                    result.back = readIdCardImg(3);
                    return result;
                } else {
                    alert("读取二代证失败！");
                }
            }
            else {
                alert("初始化二代证阅读器失败！");
            }
        }

        function AddText(obj)
        {
            if (obj.checked)
            {
                var font;
                font = plugin().Global_CreateTypeface(200, 200, 0, 0, 2, 0, 0, 0, "宋体");

                if (VideoMain)
                {
                    plugin().Video_EnableAddText(VideoMain, font, 0, 0, "文字水印", 65280, 150);
                }
                if (VideoAssist)
                {
                    plugin().Video_EnableAddText(VideoAssist, font, 0, 0, "文字水印", 65280, 150);
                }
                plugin().Font_Release(font);
            }
            else
            {
                if(VideoMain)
                {
                    plugin().Video_DisableAddText(VideoMain);
                }
                if(VideoAssist)
                {
                    plugin().Video_DisableAddText(VideoAssist);
                }
            }
        }

        function ShowProperty()
        {
            if(DeviceMain)
            {
                plugin().Device_ShowProperty(DeviceMain, MainView().View_GetObject());
            }
        }

        function Deskew(obj)
        {
            if (obj.checked)
            {
                if(VideoMain)
                {
                    plugin().Video_EnableDeskewEx(VideoMain, 1);
                }
                if(VideoAssist)
                {
                    plugin().Video_EnableDeskewEx(VideoAssist, 1);
                }
            }
            else
            {
                if(VideoMain)
                {
                    plugin().Video_DisableDeskew(VideoMain);
                }
                if(VideoAssist)
                {
                    plugin().Video_DisableDeskew(VideoAssist);
                }
            }
        }

        function SetState(obj)
        {
            if (obj.checked)
            {
                MainView().View_SetState(2);
                document.getElementById('scansize').disabled="disabled";
            }
            else
            {
                MainView().View_SetState(1);
                document.getElementById('scansize').disabled="";
            }
        }
        function OpenVerifyFacRect(obj)
        {
            if(!initFaceDetectSuccess)
            {
                alert("人脸初始化失败，机型不支持！");
                obj.checked = false;
            }
            else
            {
                if (VideoMain)
                {
                    if (obj.checked)
                        plugin().Global_EnableFaceRectCrop(VideoMain, 1);
                    else
                        plugin().Global_DisableFaceRectCrop(VideoMain);
                }
                if (VideoAssist)
                {
                    if (obj.checked)
                        plugin().Global_EnableFaceRectCrop(VideoAssist, 1);
                    else
                        plugin().Global_DisableFaceRectCrop(VideoAssist);
                }
            }
        }
        function changescansize()
        {
            var rect;
            var width =  plugin().Video_GetWidth(VideoMain);
            var heigth =  plugin().Video_GetHeight(VideoMain);

            var s = document.getElementById('scansize');
            var size = s.options.selectedIndex;

            if(size == 0)
            {
                MainView().View_SetState(1);//取消框选 状态
            }
            else if(size == 1)
            {
                rect = plugin().Global_CreateRect(width/2 - width/4, heigth/2 - heigth/4, width/2, heigth/2);
                MainView().View_SetState(2);//小尺寸
                MainView().View_SetSelectedRect(rect);

            }
            else if(size == 2)
            {
                rect = plugin().Global_CreateRect(width/2 - width/6, heigth/2 - heigth/6, width/3, heigth/3);
                MainView().View_SetState(2);//中尺寸
                MainView().View_SetSelectedRect(rect);
            }

            if(size != 0)
            {
                document.getElementById('SetState').checked = false;
                document.getElementById('SetState').disabled="disabled";
            }
            else
            {
                document.getElementById('SetState').disabled = ""
            }
        }

        function Left()
        {
            if(VideoMain)
            {
                plugin().Video_RotateLeft(VideoMain);
            }
            if(VideoAssist)
            {
                plugin().Video_RotateLeft(VideoAssist);
            }

        }

        function Right()
        {
            if(VideoMain)
            {
                plugin().Video_RotateRight(VideoMain);
            }
            if(VideoAssist)
            {
                plugin().Video_RotateRight(VideoAssist);
            }

        }

        function GetTimeString()
        {
            var date = new Date();
            var yy = date.getFullYear().toString();
            var mm = (date.getMonth() + 1).toString();
            var dd = date.getDate().toString();
            var hh = date.getHours().toString();
            var nn = date.getMinutes().toString();
            var ss = date.getSeconds().toString();
            var mi = date.getMilliseconds().toString();

            var ret = yy + mm + dd + hh + nn + ss + mi;
            return ret;
        }

        //拍照
        function Scan(type)
        {
            var video, view;
            var img_base64 = '';
            var p = plugin();
            if (type==1) {
                video = VideoAssist;
                view = AssistView();
			} else {
                video = VideoMain;
                view = MainView();
			}
            if (video) {
                var imgList = p.Video_CreateImageList(video, 0, 0);
                if (imgList) {
                    var len = p.ImageList_GetCount(imgList);
                    for (var i = 0; i < len; i++) {
                        var img = p.ImageList_GetImage(imgList, i);
                        img_base64 = p.Image_GetBase64(img, 2, 0x0100);

                        if (img_base64) {
                            view.View_PlayCaptureEffect();
                        }

                        p.Image_Release(img);
                    }

                    p.ImageList_Release(imgList);
                }
            }
            return 'data:image/jpeg;base64,' + img_base64;
        }

        /******************二代证阅读器********************/
        function StartIDCard()
        {
            if(plugin().Global_InitIdCard())
            {
                if(plugin().Global_DiscernIdCard())
                {
                    readIDcard = true;
                }
                else
                {
                    document.getElementById("idcard").value= "启动二代证阅读失败！";
                }
            }
            else
            {
                document.getElementById("idcard").value= "初始化二代证阅读器失败！";
            }
        }
        function StopIDCard()
        {
            plugin().Global_StopIdCardDiscern();
            plugin().Global_DeinitIdCard();
            readIDcard = false;
        }


        function ReadIDCard()
        {
            if(readIDcard)
            {
                alert("请先停止二代证阅读");
                return;
            }

            if(plugin().Global_InitIdCard())
            {
                var ret = plugin().Global_ReadIdCard();
                if(ret)
                {
                    var str = GetTimeString() + "：";

                    for(var i = 0; i < 16; i++)
                    {
                        str += plugin().Global_GetIdCardData(i + 1);
                        str += ";";
                    }

                    var image = plugin().Global_GetIdCardImage(1);//1表示头像， 2表示正面， 3表示反面 ...
                    plugin().Image_Save(image, "C:\\idcard.jpg", 0);
                    plugin().Image_Release(image);

                    document.getElementById("idcardimg").src= "C:\\idcard.jpg";
                    document.getElementById("idcard").value= str;
                }
                else
                {
                    document.getElementById("idcard").value= "读取二代证失败！";
                }

                plugin().Global_DeinitIdCard();
            }
            else
            {
                alert("初始化二代证阅读器失败！");
            }
        }
        /******************人脸识别********************/
        function FaceDetect()
        {
            var image1 =  readIdCardData().avatar;
            var image2 =  plugin().Global_CreateImageFromFile("C:\\2.jpg", 0);
            if(image1 && image2)
            {
                var ret = plugin().DiscernFaceDetect(image1, image2);
                if(ret != -1)
                {
                    ret += 20;
                    if(ret > 100)
                    {
                        ret = 100;
                    }
                    var msg = "识别已完成，匹配度：" + ret + "\r\n（匹配阈值为70，高于阈值则为同一人）";
                    alert(msg);
                }
                else
                {
                    alert("识别失败！");
                }
            }
            else
            {
                alert("找不到图像！");
                return;
            }

            plugin().Image_Release(image1);
            plugin().Image_Release(image2);
        }

        function VerifyFaceDetect()
        {
        	var flag = -1;
            if (VideoAssist)
            {
                var image = plugin().Video_CreateImage(VideoAssist,0, AssistView().View_GetObject())
                var idcardImage =plugin().Global_CreateImageFromBase64(readIdCardData().avatar.replace("data:image/png;base64,",""), 0);//readIdCardData().avatar

                if(image && idcardImage)
                {
                    var ret = plugin().DiscernFaceDetect(image, idcardImage);
                    if(ret != -1)
                    {
                        ret += 35;
                        if(ret > 100)
                        {
                            ret = 100;
                        }
                        var msg = "识别已完成，匹配度：" + ret + "\r\n（匹配阈值为70，高于阈值则为同一人）";
                        console.log('人脸比对值为:', msg);
                        flag = ret;
                    }
                    else
                    {
                        alert("识别失败！");
                    }
                }
                else
                {
                    alert("获取图像失败，未识别到二代证！");
                }

                plugin().Image_Release(image);
                plugin().Image_Release(idcardImage);
                return flag;
            }
        }


	</script>
</head>

<body onload="Load()" onunload="Unload()">

<div style="display: inline-block;margin: 0 auto;">
	<object id="view1" type="application/x-eloamplugin" ALLOWTRANSPARENCY="true" width="500" height="375" name="view"></object>
	<object id="view2" type="application/x-eloamplugin" ALLOWTRANSPARENCY="true" width="240" height="180" name="view"></object>
</div>
</body>
</html>